package top.jianx.music;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import top.jianx.music.api.MusicApi;
import top.jianx.music.enums.MusicProvider;
import top.jianx.music.factory.MusicApiFactory;
import top.jianx.music.model.MusicLink;
import top.jianx.music.model.Song;
import top.jianx.music.provider.netease.NeteaseSong;
import top.jianx.music.util.JtopMusicUtil;
import top.jianx.music.util.SongUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class ShawnMain {

    private final static String musicFilePath = "D:\\Users\\Administrator\\OneDrive\\桌面\\musicFile";
    public static void main(String[] args) throws IOException {
        testGetMusic(MusicProvider.Netease, 50, "黄昏");
//        testMusicLink();
    }

    @SuppressWarnings("SpellCheckingInspection")
    private static void testGetMusic(MusicProvider provider, Integer num, String keyWord) throws IOException {
        final MusicApi api = MusicApiFactory.create(provider);
        List<? extends Song> result = api.searchMusicSync(keyWord, num, true);
        if (!result.isEmpty()) {
            for (Song song : result) {
                System.out.println("===>"+JSON.toJSONString(result));
                if (StrUtil.isNotBlank(song.getMusicLink().getUrl())) {
                    testDownload(song);
                }
            }
        }
    }



    private static void testMusicLink() throws IOException {
        final MusicApi api = MusicApiFactory.create(MusicProvider.Netease);
        MusicLink result = api.getMusicLinkByIdSync("5250492");
        if (ObjectUtil.isNotEmpty(result)) {
            NeteaseSong song = new NeteaseSong();
            song.setMusicLink(result);
            System.out.println("songId:"+song.getSongId());
            String url = song.getMusicLink().getUrl();
            System.out.println("songUrl:"+url);
            if (StrUtil.isNotBlank(url)) {
                testDownload(song);
            }
        }
    }



    private static void testDownload(Song song) throws IOException {
        long l = HttpUtil.downloadFile(song.getMusicLink().getUrl(), new File(musicFilePath+"\\"+SongUtils.generateSongPath(song.getAlbum(), song)));
        System.out.println(String.format("%s[%s] ===> download music is ok !!!", song.getName(), JtopMusicUtil.getPrintSize(l)));
    }
}
